/*8
 * 
 * 合并二叉树
 * 
 * 描述

已知两颗二叉树，将它们合并成一颗二叉树。合并规则是：都存在的结点，就将结点值加起来，否则空的位置就由另一个树的结点来代替。例如：
两颗二叉树是:
                                                                    Tree 1


                                                                        Tree 2

                                                                    合并后的树为

数据范围：树上节点数量满足 
0
≤
n
≤
500
0≤n≤500，树上节点的值一定在32位整型范围内。
进阶：空间复杂度 
O
(
1
)
O(1) ，时间复杂度 
O
(
n
)
O(n)

 */
public class 合并二叉树 {
    
    public static void main(String[] args) {
        
        TreeNode node1 = new TreeNode(1);
        node1.left = new TreeNode(3);
        node1.left.left = new TreeNode(5);
        node1.right = new TreeNode(2);

        TreeNode node2 = new TreeNode(2);
        node1.left = new TreeNode(1);
        node1.left.right = new TreeNode(4);
        node1.right = new TreeNode(3);
        node1.right.right = new TreeNode(7);

        TreeNode result = mergeTrees(node1, node2);

        System.out.println(result.toString());
    }

    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     * 
     * @param t1 TreeNode类 
     * @param t2 TreeNode类 
     * @return TreeNode类
     */
    public static TreeNode mergeTrees (TreeNode t1, TreeNode t2) {
        // write code here

        if(null == t1 && null ==t2)  return null;
        if(null == t1 && null!=t2)  return t2;
        if(null == t2 && null!=t1) return t1;

        t1.val += t2.val;
        t1.left = mergeTrees(t1.left, t2.left);
        t1.right = mergeTrees(t1.right, t2.right);

        return t1;
    }
}
